// src/stores/user.js
import { defineStore } from 'pinia'
import { authApi } from '@/api/auth'

// 开发环境配置：设置为true时，每次重新启动项目都会清除登录状态
// 设置为false时，即使重启项目也会保持登录状态
const DEV_CLEAR_LOGIN_ON_RESTART = true

// 说明：
// - true: 每次运行 pnpm run dev 时显示登录页面，刷新页面保持登录
// - false: 始终保持登录状态，除非手动登出

export const useUserStore = defineStore('user', {
  state: () => {
    // 在开发环境下，检查是否为新的开发会话
    const shouldClearLogin = import.meta.env.DEV && DEV_CLEAR_LOGIN_ON_RESTART
    
    if (shouldClearLogin) {
      // 检查是否为新的开发会话（项目重启）
      const isNewDevSession = !sessionStorage.getItem('dev_session_started')
      
      if (isNewDevSession) {
        // 标记当前开发会话已启动
        sessionStorage.setItem('dev_session_started', 'true')
        
        // 清除localStorage中的登录信息（仅在项目重启时）
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')
        localStorage.removeItem('permissions')
        localStorage.removeItem('menus')
        localStorage.removeItem('tokenExpiry')
        
        console.log('🔄 检测到项目重启，已清除登录状态')
        
        
        return {
          token: '',
          userInfo: null,
          permissions: [],
          menus: [],
          tokenExpiry: null,
        }
      }
    }
    
    // 正常情况下从localStorage恢复状态（包括页面刷新）
    return {
      token: localStorage.getItem('token') || '',
      userInfo: JSON.parse(localStorage.getItem('userInfo') || 'null'),
      permissions: JSON.parse(localStorage.getItem('permissions') || '[]'),
      menus: JSON.parse(localStorage.getItem('menus') || '[]'),
      tokenExpiry: localStorage.getItem('tokenExpiry') || null,
    }
  },
  
  getters: {
    isLoggedIn: (state) => {
      if (!state.token) return false
      if (state.tokenExpiry) {
        const now = Date.now()
        const expiry = parseInt(state.tokenExpiry)
        if (now >= expiry) return false
      }
      return true
    },
    username: (state) => state.userInfo?.username || '',
    avatar: (state) => state.userInfo?.avatar || '',
    roles: (state) => state.userInfo?.roles || [],
    
    // 获取格式化的菜单数据，用于动态渲染
    formattedMenus: (state) => {
      if (!state.menus || state.menus.length === 0) return {}
      
      // 过滤掉个人中心菜单（不在导航栏显示）
      const filteredMenus = state.menus.filter(menu => menu.menuCode !== 'profile')
      
      // 按分组整理菜单
      const groupedMenus = {
        '工作台': [],
        '开发工具': [],
        '系统管理': []
      }

      console.log('🔍 过滤后的菜单:', filteredMenus)

      // 根据菜单代码获取分组
      const getMenuGroup = (menuCode) => {
        const groupMap = {
          // 工作台
          'dashboard': '工作台',
          'analytics': '工作台',
          'monitoring': '工作台',
          
          // 开发工具  
          'template-center': '开发工具',
          'templates': '开发工具',
          'create-template': '开发工具',
          'component-center': '开发工具',
          'basic-components': '开发工具',
          'icon-components': '开发工具',
          'chart-components': '开发工具',
          
          // 系统管理
          'users': '系统管理',
          'roles': '系统管理', 
          'permissions': '系统管理',
          'settings': '系统管理',
          'system': '系统管理',
          'logs': '系统管理'
        }
        
        console.log(groupMap[menuCode] || null) 

        return groupMap[menuCode] || null
      }

      // 构建菜单映射
      const menuMap = new Map()
      filteredMenus.forEach(menu => {
        const menuItem = {
          id: menu.id,
          menuCode: menu.menuCode,
          menuName: menu.menuName,
          parentId: menu.parentId,
          icon: menu.icon || 'Menu', // 修改：使用 icon 而不是 iconName
          path: menu.path,
          description: menu.description,
          children: []
        }
        menuMap.set(menu.id, menuItem)
      })

      // 按分组分类菜单
      filteredMenus.forEach(menu => {
        const group = getMenuGroup(menu.menuCode)
        if (group && groupedMenus[group]) {
          const menuItem = menuMap.get(menu.id)
          if (!menu.parentId) {
            // 只添加顶级菜单到分组中
            groupedMenus[group].push(menuItem)
          }
        }
      })

      // 构建父子关系
      filteredMenus.forEach(menu => {
        if (menu.parentId && menuMap.has(menu.parentId)) {
          const parentMenu = menuMap.get(menu.parentId)
          const childMenu = menuMap.get(menu.id)
          if (parentMenu && childMenu) {
            parentMenu.children.push(childMenu)
          }
        }
      })

      // 对菜单进行排序
      const menuOrder = {
        '工作台': ['dashboard', 'analytics', 'monitoring'],
        '开发工具': ['template-center', 'component-center', 'templates', 'create-template', 'basic-components', 'icon-components', 'chart-components'],
        '系统管理': ['users', 'roles', 'logs', 'permissions', 'settings']
      }

      Object.keys(groupedMenus).forEach(groupKey => {
        if (menuOrder[groupKey]) {
          const orderMap = menuOrder[groupKey]
          groupedMenus[groupKey].sort((a, b) => {
            const indexA = orderMap.indexOf(a.menuCode)
            const indexB = orderMap.indexOf(b.menuCode)
            // 如果找不到对应的顺序，则放到最后
            const finalIndexA = indexA === -1 ? 999 : indexA
            const finalIndexB = indexB === -1 ? 999 : indexB
            return finalIndexA - finalIndexB
          })
        }
      })

      return groupedMenus
    }
  },

  actions: {
    isDeveloperAccount(username) {
      return username && username.startsWith('888') && /^888\d{8}$/.test(username)
    },
    isRegisteredTestUser(username, password) {
      const list = JSON.parse(localStorage.getItem('registeredTestUsers') || '[]')
      return list.find(u => u.username === username && u.password === password)
    },

    async login(loginForm) {
      try {
        // 调用后端API登录
        const { authApi } = await import('@/api/auth')
        const response = await authApi.login({
          username: loginForm.username,
          password: loginForm.password
        })

        console.log('🔐 登录API响应:', response)

        // 处理后端返回的数据结构 { code: 200, message: "登录成功", data: { accessToken: "...", userInfo: {...} }, isSuccess: true }
        if (response && response.code === 200 && response.isSuccess) {
          const { accessToken, refreshToken, userInfo } = response.data
          
          // 保存token
          this.token = accessToken
          localStorage.setItem('token', this.token)

          // 设置token过期时间（24小时）
          const tokenExpiry = Date.now() + 24 * 60 * 60 * 1000
          this.tokenExpiry = tokenExpiry.toString()
          localStorage.setItem('tokenExpiry', this.tokenExpiry)

          // 保存用户信息
          this.userInfo = {
            id: userInfo?.id || null,
            username: userInfo?.username || loginForm.username,
            email: userInfo?.email || '',
            nickName: userInfo?.nickName || userInfo?.username || loginForm.username,
            avatar: userInfo?.avatar || '',
            roles: userInfo?.roles || [],
            menus: userInfo?.menus || []
          }

          console.log(userInfo.menus);
          console.log('🔍 原始菜单数据:', userInfo?.menus)
          

          console.log('🔑 用户信息:', this.userInfo)
          
          // 设置权限、角色和菜单
          this.permissions = userInfo?.permissions || []
          this.menus = userInfo?.menus || []
          this.role = userInfo?.roles?.[0]?.roleName || '用户'

          console.log(this.menus);
          

          // 保存到localStorage
          localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
          localStorage.setItem('permissions', JSON.stringify(this.permissions))
          localStorage.setItem('menus', JSON.stringify(this.menus))
          localStorage.setItem('role', this.role)

          return {
            token: this.token,
            userInfo: this.userInfo,
            permissions: this.permissions,
            menus: this.menus
          }
        } else {
          throw new Error(response?.message || '登录失败')
        }

      } catch (error) {
        console.error('❌ 登录失败:', error)
        
        // 清除可能的错误状态
        this.clearUserState()
        
        // 抛出具体的错误信息
        if (error.response?.status === 401) {
          throw new Error('用户名或密码错误')
        } else if (error.response?.status === 400) {
          throw new Error('请求参数错误')
        } else if (error.response?.status >= 500) {
          throw new Error('服务器错误，请稍后重试')
        } else {
          throw new Error(error.message || '登录失败，请检查网络连接')
        }
      }
    },

    async register(data) {
      // 注册后自动登录
      await this.login({ username: data.username, password: '123456' })
    },

    async logout() {
      this.clearUserState()
    },

    initializeUserState() {
      try {
        const token = localStorage.getItem('token')
        const userInfo = localStorage.getItem('userInfo')
        const permissions = localStorage.getItem('permissions')
        const menus = localStorage.getItem('menus')
        const tokenExpiry = localStorage.getItem('tokenExpiry')
        const role = localStorage.getItem('role')

        if (token && userInfo && permissions) {
          if (tokenExpiry && Date.now() >= parseInt(tokenExpiry)) {
            this.clearUserState()
            return false
          }
          this.token = token
          this.userInfo = JSON.parse(userInfo)
          this.permissions = JSON.parse(permissions)
          this.menus = JSON.parse(menus || '[]')
          this.tokenExpiry = tokenExpiry
          this.role = role
          return true
        }
      } catch {
        this.clearUserState()
      }
      return false
    },

    clearUserState() {
      this.token = ''
      this.userInfo = null
      this.permissions = []
      this.menus = []
      this.tokenExpiry = ''
      this.role = ''
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      localStorage.removeItem('permissions')
      localStorage.removeItem('menus')
      localStorage.removeItem('tokenExpiry')
      localStorage.removeItem('role')
    },

    hasPermission(permission) {
      if (!permission) return true
      
      // 超级管理员拥有所有权限
      if (this.userInfo?.username === 'superadmin' || this.userInfo?.username === 'admin') {
        return true
      }
      
      // 检查是否为系统角色，系统角色拥有对应的权限
      const userRoles = this.userInfo?.roles || []
      const isSystemRole = userRoles.some(role => role.code === 'super_admin' || role.code === 'system_admin')
      
      if (isSystemRole) {
        return true
      }
      
      // 检查用户权限列表
      if (Array.isArray(this.permissions)) {
        return this.permissions.some(p => {
          if (typeof p === 'string') {
            return p === permission
          }
          return p.code === permission || p.permissionCode === permission
        })
      }
      
      // 临时权限映射（在后端权限系统完全实现前）
      const tempPermissions = {
        // 基础权限
        'dashboard.view': true,
        'profile.view': true,
        'profile.update': true,
        
        // 用户管理权限
        'user.view': this.token && (this.userInfo?.username === 'admin' || this.hasRole('system_admin')),
        'user.create': this.token && (this.userInfo?.username === 'admin' || this.hasRole('system_admin')),
        'user.update': this.token && (this.userInfo?.username === 'admin' || this.hasRole('system_admin')),
        'user.delete': this.token && (this.userInfo?.username === 'admin' || this.hasRole('system_admin')),
        'user.assign': this.token && (this.userInfo?.username === 'admin' || this.hasRole('system_admin')),
        'user.resetPassword': this.token && (this.userInfo?.username === 'admin' || this.hasRole('system_admin')),
        'user.search': this.token,
        
        // 角色管理权限
        'role.view': this.token && (this.userInfo?.username === 'admin' || this.hasRole('system_admin')),
        'role.create': this.token && (this.userInfo?.username === 'admin' || this.hasRole('super_admin')),
        'role.update': this.token && (this.userInfo?.username === 'admin' || this.hasRole('super_admin')),
        'role.delete': this.token && (this.userInfo?.username === 'admin' || this.hasRole('super_admin')),
        'role.assign': this.token && (this.userInfo?.username === 'admin' || this.hasRole('system_admin')),
        'role.menu': this.token && (this.userInfo?.username === 'admin' || this.hasRole('super_admin')),
        'role.status': this.token && (this.userInfo?.username === 'admin' || this.hasRole('super_admin')),
        
        // 权限管理权限
        'permission.view': this.token && (this.userInfo?.username === 'admin' || this.hasRole('system_admin')),
        'permission.create': this.token && (this.userInfo?.username === 'admin' || this.hasRole('super_admin')),
        'permission.update': this.token && (this.userInfo?.username === 'admin' || this.hasRole('super_admin')),
        'permission.delete': this.token && (this.userInfo?.username === 'admin' || this.hasRole('super_admin')),
        'permission.tree': this.token && (this.userInfo?.username === 'admin' || this.hasRole('system_admin')),
        'permission.status': this.token && (this.userInfo?.username === 'admin' || this.hasRole('super_admin')),
        
        // 菜单管理权限
        'menu.view': this.token && (this.userInfo?.username === 'admin' || this.hasRole('system_admin')),
        'menu.create': this.token && (this.userInfo?.username === 'admin' || this.hasRole('super_admin')),
        'menu.update': this.token && (this.userInfo?.username === 'admin' || this.hasRole('super_admin')),
        'menu.delete': this.token && (this.userInfo?.username === 'admin' || this.hasRole('super_admin')),
        'menu.sort': this.token && (this.userInfo?.username === 'admin' || this.hasRole('super_admin')),
        'menu.assign': this.token && (this.userInfo?.username === 'admin' || this.hasRole('super_admin')),
        
        // 分析权限
        'analytics.dashboard': this.token,
        'analytics.chart': this.token,
        'analytics.realtime': this.token && (this.userInfo?.username === 'admin' || this.hasRole('data_analyst')),
        
        // 日志权限
        'log.view': this.token && (this.userInfo?.username === 'admin' || this.hasRole('devops')),
        'log.delete': this.token && (this.userInfo?.username === 'admin' || this.hasRole('super_admin')),
        'log.search': this.token && (this.userInfo?.username === 'admin' || this.hasRole('devops')),
        
        // 监控权限
        'monitoring.system': this.token && (this.userInfo?.username === 'admin' || this.hasRole('devops')),
        'monitoring.performance': this.token && (this.userInfo?.username === 'admin' || this.hasRole('devops')),
        'monitoring.alerts': this.token && (this.userInfo?.username === 'admin' || this.hasRole('devops')),
        
        // 模板组件权限
        'template.view': this.token,
        'template.create': this.token && (this.userInfo?.username === 'admin' || this.hasRole('developer')),
        'template.edit': this.token && (this.userInfo?.username === 'admin' || this.hasRole('developer')),
        'template.delete': this.token && (this.userInfo?.username === 'admin' || this.hasRole('super_admin')),
        'component.view': this.token,
        'component.manage': this.token && (this.userInfo?.username === 'admin' || this.hasRole('developer')),
        
        // 系统设置权限
        'system.settings': this.token && (this.userInfo?.username === 'admin' || this.hasRole('system_admin'))
      }
      
      return tempPermissions[permission] || false
    },

    hasRole(role) {
      if (!role) return true
      const userRoles = this.userInfo?.roles || []
      return userRoles.some(r => r.code === role || r.roleCode === role)
    },

    // 获取用户可访问的菜单列表
    getUserMenus() {
      if (this.userInfo?.username === 'superadmin' || this.userInfo?.username === 'admin') {
        // 返回完整菜单结构
        return [
          {
            id: 'dashboard',
            code: 'dashboard',
            name: '仪表盘',
            path: '/dashboard',
            icon: 'Dashboard'
          },
          {
            id: 'system',
            code: 'system',
            name: '系统管理',
            icon: 'Setting',
            children: [
              {
                id: 'user-management',
                code: 'user_management',
                name: '用户管理',
                path: '/system/users',
                icon: 'User'
              },
              {
                id: 'role-management',
                code: 'role_management',
                name: '角色管理',
                path: '/system/roles',
                icon: 'UserFilled'
              },
              {
                id: 'permission-management',
                code: 'permission_management',
                name: '权限管理',
                path: '/system/permissions',
                icon: 'Key'
              },
              {
                id: 'menu-management',
                code: 'menu_management',
                name: '菜单管理',
                path: '/system/menus',
                icon: 'Menu'
              }
            ]
          }
        ]
      }
      
      // 使用从后端获取的菜单数据
      return this.menus || []
    },

    // 更新用户头像
    updateAvatar(avatarUrl) {
      if (this.userInfo) {
        this.userInfo = {
          ...this.userInfo,
          avatar: avatarUrl
        }
        localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
        console.log('✅ 头像更新成功:', avatarUrl)
      }
    },
    
    // 更新用户信息
    updateUserInfo(userProfile) {
      if (this.userInfo && userProfile) {
        this.userInfo = {
          ...this.userInfo,
          id: userProfile.id || this.userInfo.id,
          username: userProfile.username || this.userInfo.username,
          nickName: userProfile.nickName || this.userInfo.nickName,
          email: userProfile.email || this.userInfo.email,
          avatar: userProfile.avatar || this.userInfo.avatar,
          description: userProfile.description || this.userInfo.description
        }
        localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
        console.log('✅ 用户信息更新成功:', this.userInfo)
      }
    }
  }
})